<?php

namespace App\Http\Requests;

use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;

abstract class BaseRequest extends Request
{
    /**
     * 获取验证规则
     *
     * @return array
     */
    abstract public function rules(): array;

    /**
     * 获取验证错误消息
     *
     * @return array
     */
    public function messages(): array
    {
        return [];
    }

    /**
     * 获取自定义属性名称
     *
     * @return array
     */
    public function attributes(): array
    {
        return [];
    }

    /**
     * 验证请求数据
     *
     * @throws ValidationException
     */
    public function validateResolved()
    {
        $validator = app('validator')->make(
            $this->all(),
            $this->rules(),
            $this->messages(),
            $this->attributes()
        );

        if ($validator->fails()) {
            $this->failedValidation($validator);
        }
    }

    /**
     * 处理验证失败
     *
     * @param Validator $validator
     * @throws ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        throw new ValidationException($validator);
    }
}